package cn.nexttec.noteplayer.ui.activities

import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.PermissionHelper
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.events.FileScanDoneEvent
import cn.nexttec.noteplayer.service.FileScanService
import cn.nexttec.noteplayer.ui.widget.ParticleView.ParticleView
import cn.nexttec.noteplayer.ui.widget.PopupDialog
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

@AndroidEntryPoint
class SplashAcitivity : AppCompatActivity(), ParticleView.ParticleAnimListener {
    @Inject lateinit var preference: Preference
    lateinit var serviceConnection: ServiceConnection
    lateinit var fileScanService: FileScanService
    private var handler: Handler = Handler(Looper.getMainLooper())
    private var hasPermission = false
    private val TAG = "SplashAcitivity"
    private var isRequestingPermission = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash_acitivity)
        window.statusBarColor = ContextCompat.getColor(this, R.color.white)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
        serviceConnection = FileScanService.bind(this@SplashAcitivity, onConnected = {
            fileScanService = it
        })


        if (!PermissionHelper.isPermissionGranted(this@SplashAcitivity)) {
            hasPermission = false
            handler.postDelayed({
                isRequestingPermission = true
                PopupDialog.showStoragePermissionRequestDialog(
                    onConfirm = {
                        PermissionHelper.requestStoragePermission(
                            this,
                            object : PermissionHelper.PermissionCallback {
                                override fun onGranted() {
                                    // 权限通过，可以扫描 SD 卡等文件了
                                    if (::fileScanService.isInitialized) {
                                        fileScanService.scanVideoFiles()
                                    }
                                    playLogo()
                                }

                                override fun onDenied() {
                                    Toast.makeText(
                                        this@SplashAcitivity,
                                        "权限被拒绝，无法访问 SD 卡",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            })
                    },
                    onReject = {
                        System.exit(0)
                    }
                )
            }, 500L)

        } else {
            hasPermission = true
            if (::fileScanService.isInitialized) {
                fileScanService.scanVideoFiles()
            }
            playLogo()
        }

    }

    override fun onResume() {
        super.onResume()
        if (!hasPermission){
            if (!PermissionHelper.isPermissionGranted(this@SplashAcitivity)){
                if (isRequestingPermission) {
                    TAG debug "PermissionDenied"
                    AlertDialog.Builder(this@SplashAcitivity)
                        .setTitle("提示")
                        .setMessage("存储权限没有授予，你还是自己数手指玩吧，点击\"确定\"退出本软件，直接卸载，88不见！")
                        .setPositiveButton("确定") { _, _ ->
                            System.exit(0)
                        }
                        .show()
                } else {
                    TAG debug "not isRequestingPermission"
                }
            } else {
                if (::fileScanService.isInitialized) {
                    fileScanService.scanVideoFiles()
                }
                playLogo()

            }
        } else {

            playLogo()
        }
    }
    private fun playLogo() {
        if (!preference.isSkipAnimation) {
            this.findViewById<View>(R.id.rl_welcome).visibility = View.GONE
            val particleView = findViewById<ParticleView>(R.id.particalView)
            particleView.setOnParticleAnimListener(this@SplashAcitivity)
            particleView.startAnim()
        } else {
            this.findViewById<View>(R.id.rl_welcome).visibility = View.VISIBLE
            onAnimationEnd()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::serviceConnection.isInitialized) {
            unbindService(serviceConnection)
        }
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }


    override fun onAnimationEnd() {
        handler.postDelayed({
            startActivity(Intent(this@SplashAcitivity, MainActivity::class.java))
            this.finish()
        }, 1000L)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onScanDone(e:FileScanDoneEvent){
        preference.isScanfinished = true
    }

    fun setImmersiveMode() {
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                )
        actionBar?.hide()
        supportActionBar?.hide()
    }


}